package com.example1.myapplication1;

import android.Manifest;
import android.content.pm.PackageManager;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_LOCATION = 100;
    private static final String TAG = "NetworkScan";
    private static final String[] HOTSPOT_SEGMENTS = {
            "192.168.43.", "192.168.42.", "192.168.44.",
            "192.168.137.", "192.168.173.", "192.168.39."
    };

    // UI组件
    private Button btnScan;
    private ProgressBar progressBar;
    private ProgressBar horizontalProgress;
    private TextView tvProgress;
    private ListView listView;
    private ArrayAdapter<String> adapter;
    private List<String> activeIps = new ArrayList<>();

    // 扫描控制
    private ExecutorService executor;
    private AtomicInteger totalTasks = new AtomicInteger(0);
    private AtomicInteger completedTasks = new AtomicInteger(0);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        setupButtonListener();
    }

    private void initViews() {
        btnScan = findViewById(R.id.btn_scan);
        progressBar = findViewById(R.id.progressBar);
        horizontalProgress = findViewById(R.id.horizontalProgress);
        tvProgress = findViewById(R.id.tv_progress);
        listView = findViewById(R.id.listView);

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, activeIps);
        listView.setAdapter(adapter);
        horizontalProgress.setMax(100);
        tvProgress.setText("0%");
    }

    private void setupButtonListener() {
        btnScan.setOnClickListener(v -> {
            if (checkPermissions()) {
                startScan();
            }
        });
    }

    private void startScan() {
        resetScanState();
        initThreadPool();
        submitScanTasks();
        startProgressMonitor();
        awaitTermination();
    }

    // Android 14 兼容性改进的核心方法
    private void submitScanTasks() {
        Set<String> targetIPs = new HashSet<>();

        // 1. 通过ARP表获取已连接设备
        targetIPs.addAll(getArpTableIps());

        // 2. 获取当前有效网络段
        String currentSegment = getCurrentNetworkSegment();
        if (currentSegment != null) {
            Log.d(TAG, "当前网络段: " + currentSegment);
            for (int i = 1; i <= 254; i++) {
                targetIPs.add(currentSegment + i);
            }
        }

        // 3. 添加常见热点段
        for (String segment : HOTSPOT_SEGMENTS) {
            for (int i = 1; i <= 254; i++) {
                targetIPs.add(segment + i);
            }
        }

        totalTasks.set(targetIPs.size());

        // 提交扫描任务
        for (String ip : targetIPs) {
            executor.execute(() -> processIp(ip));
        }
    }

    // 增强ARP表解析（Android 14兼容）
    private List<String> getArpTableIps() {
        List<String> arpIps = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"))) {
            String line;
            br.readLine(); // 跳过标题行
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\s+");
                if (parts.length >= 6 && "0x2".equals(parts[2])) { // 0x2表示已连接
                    arpIps.add(parts[0]);
                }
            }
            Log.d(TAG, "从ARP表发现设备: " + arpIps.size());
        } catch (IOException e) {
            Log.e(TAG, "读取ARP表失败", e);
        }
        return arpIps;
    }

    // 改进的网络段检测方法
    private String getCurrentNetworkSegment() {
        try {
            // 优先通过DHCP信息获取
            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
            if (wifiManager.isWifiEnabled()) {
                DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
                if (dhcpInfo != null) {
                    String gateway = intToIp(dhcpInfo.gateway);
                    Log.d(TAG, "DHCP网关: " + gateway);
                    return getSegmentFromIp(gateway);
                }
            }

            // 遍历网络接口
            for (NetworkInterface netInterface :
                    Collections.list(NetworkInterface.getNetworkInterfaces())) {
                if (isValidInterface(netInterface)) {
                    for (InetAddress address :
                            Collections.list(netInterface.getInetAddresses())) {
                        if (address instanceof Inet4Address &&
                                !address.isLoopbackAddress()) {
                            String ip = address.getHostAddress();
                            Log.d(TAG, "发现有效IP: " + ip);
                            return getSegmentFromIp(ip);
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "网络段检测异常", e);
        }
        return "192.168.43."; // 默认回退
    }

    // 增强的网络接口验证
    private boolean isValidInterface(NetworkInterface netInterface) {
        try {
            return netInterface.isUp() &&
                    !netInterface.isLoopback() &&
                    !netInterface.isVirtual() &&
                    (netInterface.getName().startsWith("wlan") ||
                            netInterface.getName().startsWith("ap") ||
                            netInterface.getName().startsWith("rndis"));
        } catch (SocketException e) {
            return false;
        }
    }

    // 改进的IP可达性检测
    private boolean isReachable(String ip) {
        try {
            // 双重检测机制
            boolean arpFound = checkArpCache(ip);
            boolean pingResult = InetAddress.getByName(ip).isReachable(500);

            Log.d(TAG, "检测IP: " + ip +
                    " ARP:" + arpFound +
                    " PING:" + pingResult);

            return arpFound || pingResult;
        } catch (IOException e) {
            Log.w(TAG, "IP检测失败: " + ip, e);
            return false;
        }
    }

    // 检查ARP缓存
    private boolean checkArpCache(String ip) {
        try (BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains(ip)) {
                    return true;
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "检查ARP缓存失败", e);
        }
        return false;
    }

    // 其他辅助方法保持不变（需保留原有代码结构）
    private void processIp(String ip) {
        try {
            if (isReachable(ip)) {
                addDiscoveredIp(ip);
            }
        } finally {
            updateProgress();
        }
    }

    private void addDiscoveredIp(String ip) {
        runOnUiThread(() -> {
            if (!activeIps.contains(ip)) {
                activeIps.add(ip);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void updateProgress() {
        int progress = (int) ((completedTasks.incrementAndGet() * 100f) / totalTasks.get());
        runOnUiThread(() -> {
            horizontalProgress.setProgress(progress);
            tvProgress.setText(progress + "%");
        });
    }

    private void initThreadPool() {
        int poolSize = Runtime.getRuntime().availableProcessors() * 4;
        executor = Executors.newFixedThreadPool(poolSize);
    }

    private void startProgressMonitor() {
        new Thread(() -> {
            while (!executor.isTerminated()) {
                try {
                    Thread.sleep(200);
                    Log.d(TAG, "扫描进度: " + tvProgress.getText());
                } catch (InterruptedException e) {
                    break;
                }
            }
        }).start();
    }

    private void awaitTermination() {
        executor.shutdown();
        new Thread(() -> {
            try {
                if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
                    showToast("扫描完成（部分结果可能缺失）");
                }
                scanComplete();
            } catch (InterruptedException e) {
                handleInterruption(e);
            }
        }).start();
    }

    private void scanComplete() {
        runOnUiThread(() -> {
            progressBar.setVisibility(View.GONE);
            horizontalProgress.setVisibility(View.GONE);
            tvProgress.setVisibility(View.GONE);
            btnScan.setEnabled(true);
            showToast("发现 " + activeIps.size() + " 个设备");
        });
    }

    private void handleInterruption(InterruptedException e) {
        runOnUiThread(() -> {
            showToast("扫描被中断");
            if (executor != null) {
                executor.shutdownNow();
            }
        });
        Thread.currentThread().interrupt();
    }

    private String getSegmentFromIp(String ip) {
        return ip.substring(0, ip.lastIndexOf('.') + 1);
    }

    private static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
    }

    private boolean checkPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_LOCATION && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startScan();
        }
    }

    private void showToast(String message) {
        runOnUiThread(() -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
    }

    private void resetScanState() {
        // 新增计数器重置
        completedTasks.set(0);
        totalTasks.set(0); 
        
        runOnUiThread(() -> {
            btnScan.setEnabled(false);
            progressBar.setVisibility(View.VISIBLE);
            horizontalProgress.setVisibility(View.VISIBLE);
            tvProgress.setVisibility(View.VISIBLE);
            activeIps.clear();
            adapter.notifyDataSetChanged();
            horizontalProgress.setProgress(0);
            tvProgress.setText("0%");
        });
    }
}